package progress.exa2;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class OutputStreamStudy {

    public static void main(String[] args) throws IOException {
        //writeStudy();
        writeBytesStudy();
        //writeBytesLenStudy();
        //flushStudy();
    }

    /**
     * 每次写入单个字节
     * @throws IOException
     */
    public static void writeStudy() throws IOException {
        OutputStream outputStream = new FileOutputStream("四郎.txt");
        String str = "我是四郎";
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        for (byte b:bytes){
            outputStream.write(b);
        }
        System.out.println("成功写入,请检查是否生成了文件： 四郎.txt ");
    }

    /**
     * 一次写入多个字节
     * @throws IOException
     */
    public static void writeBytesStudy() throws IOException {
        OutputStream outputStream = new FileOutputStream("四郎.txt");
        String str = "我是四郎";
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        outputStream.write(bytes);
        System.out.println("成功写入,请检查是否生成了文件： 四郎.txt ");
    }

    /**
     * 从指定字节数组中选一部分进行写入
     * @throws IOException
     */
    public static void writeBytesLenStudy() throws IOException {
        OutputStream outputStream = new FileOutputStream("四郎.txt");
        String str = "我是四郎";
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        outputStream.write(bytes,2,2);
        System.out.println("成功写入,请检查是否生成了文件： 四郎.txt ");
    }

    /**
     * 对于缓冲输出流，它的write方法并不会立即向磁盘中写入数据，
     * 而需要缓存满了或者调用flush方法立即写入
     * @throws IOException
     */
    public static void flushStudy() throws IOException {
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("四郎.txt"));
        String str = "我是四郎";
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        outputStream.write(bytes);
        outputStream.flush();
        System.out.println("成功写入,请检查是否生成了文件： 四郎.txt ");
    }


}
